from pathlib import Path
from typing import Dict, Optional
from .base import BaseTTSEngine


class GTTSttsEngine(BaseTTSEngine):
    """
    gTTS在线TTS引擎实现
    """
    
    def __init__(self, config: Optional[Dict] = None):
        super().__init__(config)
        self.has_gtts = False
        self.gtts = None
        self.initialize()
    
    def initialize(self) -> bool:
        """
        初始化gTTS引擎
        """
        try:
            from gtts import gTTS
            self.gtts = gTTS
            self.has_gtts = True
            self.initialized = True
            print("✓ gTTS引擎初始化成功")
            return True
        except ImportError:
            print("✗ gTTS引擎初始化失败: 未安装gTTS库")
            return False
    
    def synthesize(self, text: str, output_path: Path, lang: str = "en") -> bool:
        """
        使用gTTS进行语音合成
        """
        if not self.is_available():
            print(f"  ⚠ gTTS引擎不可用，无法合成文本: {text}")
            return False
        
        try:
            tts = self.gtts(text=text, lang=lang)
            tts.save(str(output_path))
            print(f"  ✓ 生成音节语音: {text} -> {output_path.name} (gTTS)")
            return True
        except Exception as e:
            print(f"  ⚠ gTTS失败: {e}")
            return False
    
    def is_available(self) -> bool:
        """
        检查gTTS引擎是否可用
        """
        return self.has_gtts and self.initialized
    
    def get_name(self) -> str:
        """
        获取引擎名称
        """
        return "gTTS"